$(document).ready(function() {

    var start_price_prev_val = $("#start-price").val();
    var start_annual_fee_prev_val = $("#start-annual-fee").val();

    processContractType();
    setSizeOfGuaranteeFee(start_price_prev_val);

    $("#conditions-of-contract-type").change(function () {
        processContractType();
    });

    function processContractType() {
        var contract_type = parseInt($("#conditions-of-contract-type").val());

        switch(contract_type) {
            case 1: // Купівлі-продажу
                enableStartPrice();
                break;
            case 2: // Оренди
                enableStartAnnualFee();
                break;
            case 3: // Суперфіцію
                enableStartAnnualFee();
                break;
            case 4: // Емфітевзису
                enableStartAnnualFee();
                break;
            default:
                break;
        }
    }

    function enableStartPrice() {
        if($("#start-price").attr("readonly")) {
            $("#start-price").val(start_price_prev_val);
            $("#start-price").removeAttr("readonly");
            setSizeOfGuaranteeFee(start_price_prev_val);
            $("#start-price-item").show();
        }

        if(!$("#start-annual-fee").attr("readonly")) {
            start_annual_fee_prev_val = $("#start-annual-fee").val();
            $("#start-annual-fee").val("0.00");
            $("#start-annual-fee").attr("readonly", "readonly");
            $("#start-annual-fee-item").hide();
        }
    }

    function enableStartAnnualFee() {
        if(!$("#start-price").attr("readonly")) {
            start_price_prev_val = $("#start-price").val();
            $("#start-price").val("0.00");
            $("#start-price").attr("readonly", "readonly");
            $("#start-price-item").hide();
        }

        if($("#start-annual-fee").attr("readonly")) {
            $("#start-annual-fee").val(start_annual_fee_prev_val);
            $("#start-annual-fee").removeAttr("readonly");
            setSizeOfGuaranteeFee(start_annual_fee_prev_val);
            $("#start-annual-fee-item").show();
        }
    }

    function setSizeOfGuaranteeFee(value) {
        var expr = /^\d+\.\d{2}$/;
        if(expr.test(value)) {
            var money = parseFloat(value) * 0.1;
            money = money.toFixed(2);
            $("#size-of-guarantee-fee").val(money);
        }else {
            $("#size-of-guarantee-fee").val("0.00");
        }
    }

    jQuery.validator.addMethod("money", function(value, element) {
        var expr = /^\d+\.\d{2}$/;
        return this.optional(element) || expr.test(value);
    }, "Будь ласка, введіть вірне грошове значення.");
    $("#editForm").validate();

    $("#start-price").change(function() {
        setSizeOfGuaranteeFee($(this).val());
    });

    $("#start-annual-fee").change(function() {
        setSizeOfGuaranteeFee($(this).val());
    });

});
